package com.kepus.service.mgruser;

import com.kepus.common.constant.ConstApp;
import com.kepus.common.domainobject.DOCommon;
import com.kepus.common.domainobject.DOPage;
import com.kepus.common.domainobject.userMgr.DOUser;
import com.kepus.common.enumeration.EnumRole;
import com.kepus.common.persistenceobject.usermgr.POUser;
import com.kepus.dao.UserMgrDao;
import com.kepus.service.cache.LoginedUserCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 巩聪 on 2018/6/15.
 */
@Service
public class UserMgrService {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserMgrService.class);
    @Autowired
    private UserMgrDao userMgrDao;

    public DOCommon login(String sessionId, String userName, String passwd)
    {
        DOCommon returnDO = new DOCommon();
        DOPage doPage = new DOPage();
        Map<String, Object> params = new LinkedHashMap();
        params.put("userName", userName);
        params.put("passwd", passwd);
        doPage.setParams(params);
        List<DOUser> lstDOUser = userMgrDao.queryUser(doPage);
        if(CollectionUtils.isEmpty(lstDOUser))
        {
            LOGGER.info("{}/{} not exist.", userName, passwd);
            returnDO.setSuccess(false);
            returnDO.setMsg("uesr not exist.");
        }
        else if(lstDOUser.size() > 1)
        {
            LOGGER.info("{} more than one user, may not change password..", userName, passwd);
            returnDO.setSuccess(false);
            returnDO.setMsg("please change password.");
        }else {
            returnDO.setSuccess(true);
            LoginedUserCache.add(sessionId, lstDOUser.get(ConstApp.LIST_FIRST_ELEMENt));
        }
        return returnDO;
    }

    public EnumRole queryUserRole(String sessionId, String userName) {
        LoginedUserCache.UserCachedInfo userCachedInfo = LoginedUserCache.get(sessionId);
        return userCachedInfo.getRole();
    }
    public void regist(List<DOUser> lstDOUser)
    {
        userMgrDao.createUser(lstDOUser);
    }
}
